package com.sendpo.zjx.sendpo.activity;

import android.app.Dialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.sendpo.zjx.sendpo.R;
import com.sendpo.zjx.sendpo.net.HttpCode;
import com.sendpo.zjx.sendpo.net.HttpUrl;
import com.sendpo.zjx.sendpo.services.AmapLocationService;
import com.sendpo.zjx.sendpo.table.User;
import com.sendpo.zjx.sendpo.utils.Tools;
import com.sendpo.zjx.sendpo.utils.Xutils;
import com.sendpo.zjx.sendpo.views.CustomDatePicker;
import com.sendpo.zjx.sendpo.views.MainScrollview;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2017/8/21.
 */

public class HelpingSubmitInfoActivity extends AppCompatActivity implements AMapLocationListener {
    public Dialog loadingdialog = null;
    @BindView(R.id.backbt)
    RelativeLayout backbt;
    @BindView(R.id.head)
    RelativeLayout head;

    @BindView(R.id.title_tv)
    TextView titleTv;
    @BindView(R.id.title_edit)
    EditText titleEdit;
    @BindView(R.id.money_tv)
    TextView moneyTv;
    @BindView(R.id.money_spinner)
    Spinner moneySpinner;
    @BindView(R.id.money_edit)
    EditText moneyEdit;
    @BindView(R.id.contentinfo)
    EditText contentinfo;
    @BindView(R.id.maincrollview)
    MainScrollview maincrollview;
    @BindView(R.id.tools_tv)
    TextView toolsTv;
    @BindView(R.id.tools_edit)
    EditText toolsEdit;
    @BindView(R.id.start_time_tv)
    TextView startTimeTv;
    @BindView(R.id.start_time)
    TextView startTime;
    @BindView(R.id.starttime_bt)
    RelativeLayout starttimeBt;
    @BindView(R.id.peoplenum_tv)
    TextView peoplenumTv;
    @BindView(R.id.peoplenum_edit)
    EditText peoplenumEdit;
    @BindView(R.id.iphone_tv)
    TextView iphoneTv;
    @BindView(R.id.iphone_edit)
    EditText iphoneEdit;
    private CustomDatePicker customDatePicker1;
    public AmapLocationService amapLocationService;
    private String city = "";
    private String province = "";
    private String area = "";
    private String longitude = "";
    private String latitude = "";
    private String start_time = "";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_subtmithelpinginfo);
        ButterKnife.bind(this);
        Tools.initStatus(this, R.color.black);
        initComponent();
    }

    private void initComponent() {
        amapLocationService = new AmapLocationService(this);

        amapLocationService.registerListener(this);
        amapLocationService.setmLocationOption(getDefaultAmapLocationOptions());
        amapLocationService.start();

        loadingdialog = new Dialog(this);
        loadingdialog.setContentView(R.layout.dialog_loading);
        loadingdialog.setCanceledOnTouchOutside(false);
        loadingdialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        initDatePicker();
    }

    public AMapLocationClientOption getDefaultAmapLocationOptions() {
        AMapLocationClientOption mLocationOption = null;
        if (mLocationOption == null) {
            mLocationOption = new AMapLocationClientOption();
            //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            mLocationOption.setLocationCacheEnable(true);
            //         mLocationOption.setOnceLocation(true);
            mLocationOption.setOnceLocationLatest(false);
            //设置是否返回地址信息（默认返回地址信息）
            mLocationOption.setNeedAddress(true);
            //设置是否强制刷新WIFI，默认为true，强制刷新。
            mLocationOption.setWifiScan(true);
            mLocationOption.setInterval(3000);
            //单位是毫秒，默认30000毫秒，建议超时时间不要低于8000毫秒。
            mLocationOption.setHttpTimeOut(20000);
        }
        return mLocationOption;
    }

    @OnClick(value = {R.id.backbt, R.id.bottom, R.id.starttime_bt})
    public void onMyClick(View view) {
        switch (view.getId()) {
            case R.id.backbt:
                finish();
                break;
            case R.id.bottom:
                if (TextUtils.isEmpty(titleEdit.getText().toString().trim())) {
                    Toast.makeText(getApplicationContext(), "标题不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(startTime.getText().toString().trim())) {
                    Toast.makeText(getApplicationContext(), "预计到达时间不能没有", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(peoplenumEdit.getText().toString().trim())) {
                    Toast.makeText(getApplicationContext(), "需求人数", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!Tools.isInteger(peoplenumEdit.getText().toString().trim())) {
                Toast.makeText(getApplicationContext(), "不是个整数字", Toast.LENGTH_SHORT).show();
            }
            int is = Integer.parseInt(peoplenumEdit.getText().toString().trim());
            if (is == 0) {
                Toast.makeText(getApplicationContext(), "人数不能为0", Toast.LENGTH_SHORT).show();
            }
            if (TextUtils.isEmpty(iphoneEdit.getText().toString().trim())) {
                Toast.makeText(getApplicationContext(), "联系方式不能为空", Toast.LENGTH_SHORT).show();
                return;
            }

            if (TextUtils.isEmpty(moneyEdit.getText().toString().trim())) {
                Toast.makeText(getApplicationContext(), "金钱不能没有", Toast.LENGTH_SHORT).show();
                return;
            }

                int money_int = Integer.parseInt(peoplenumEdit.getText().toString().trim());
                if (money_int == 0) {
                    Toast.makeText(getApplicationContext(), "金额不能为0", Toast.LENGTH_SHORT).show();
                }

            if (TextUtils.isEmpty(contentinfo.getText().toString().trim())) {
                Toast.makeText(getApplicationContext(), "描述不能为空", Toast.LENGTH_SHORT).show();
                return;
            }

            submit(titleEdit.getText().toString().trim(),
                    toolsEdit.getText().toString().trim(),
                    peoplenumEdit.getText().toString().trim() + "",
                    0 + "",
                    moneyEdit.getText().toString().trim(),
                    iphoneEdit.getText().toString().trim(),
                    contentinfo.getText().toString().trim(),
                    startTime.getText().toString().trim()
                    );
            break;
            case R.id.starttime_bt:
                customDatePicker1.show(new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA).format(new Date()));
                break;

        }
    }

    private void initDatePicker() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
        String now = sdf.format(new Date(new Date().getTime() + 1000 * 60 * 60 * 24));
        customDatePicker1 = new CustomDatePicker(this, new CustomDatePicker.ResultHandler() {
            @Override
            public void handle(String time) { // 回调接口，获得选中的时间
                //   currentDate.setText(time.split(" ")[0]);
                start_time=time;
                startTime.setText(time);
            }
        }, "2010-01-01 00:00", now); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
        customDatePicker1.showSpecificTime(true); // 不显示时和分
        customDatePicker1.setIsLoop(true); // 不允许循环滚动


    }

    public void submit(String helpTitle, String helpTools, String helpPeoplenum,
                       String helpType, String helpMoney,
                       String helpIphone, String helpInfo,
                       String helpYuyuedatetime) {
        List<User> userList = Xutils.queryAll(getApplication(), User.class);
        if (userList == null || userList.size() == 0) {
            return;
        }
        User user = userList.get(0);
        Map<String, String> map = new HashMap<>();
System.out.println("***************"+user.getUserId());
        map.put("userId", "" + user.getUserId());
        map.put("helpTitle", "" + helpTitle);
        map.put("helpProvince", "" + province);
        map.put("helpArea", "" + area);
        map.put("helpCity", "" + city);
        map.put("helpLongitude", "" + longitude);
        map.put("helpLatitude", "" + latitude);
        map.put("helpTools", "" + helpTools);
        map.put("helpPeoplenum", "" + helpPeoplenum);
        map.put("helpType", "" + helpType);
        map.put("helpMoney", "" + helpMoney);
        map.put("helpIphone", "" + helpIphone);
        map.put("helpInfo", "" + helpInfo);
        map.put("helpYuyuedatetime", "" + helpYuyuedatetime);

        loadingdialog.show();
        Xutils.POST(HttpUrl.userneedhelpaddmap, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                loadingdialog.dismiss();
                try {
                    JSONObject jsonObject=new JSONObject(result);
                    Toast.makeText(getApplicationContext(), ""+jsonObject.getString("message"), Toast.LENGTH_SHORT).show();
                    switch (jsonObject.getInt("state")){
                        case HttpCode.SUCCESS:
                           finish();
                            break;
                        case HttpCode.ERROR:
                            break;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                loadingdialog.dismiss();
                Toast.makeText(getApplicationContext(), "请稍后再试", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null) {
            province = aMapLocation.getProvince();
            city = aMapLocation.getCity();
            area = aMapLocation.getDistrict();
            longitude = aMapLocation.getLongitude() + "";
            latitude = aMapLocation.getLatitude() + "";
        }
    }
}
